const Auth = require('./auth')
const config = require('../../static/config')
const {Request} = require('./request')

// import Flyio from 'andy-flyio/dist/npm/wx'

let Flyio = require('../../static/flyio/wx')

let notTokenPath = [
  'token/create',
  'user/create',
  'check/student/identity',
  'check/student/registered',
  'register/status',
  'province/city',
  'school'
]

let authSysPath = [
  'token/create',
  'user/create',
  'code/gen',
  'register/status',
]

function checkIncludes(arr, url) {
  let flag = false
  arr.forEach(v => {
    if (url.indexOf(v) > -1) {
      flag = true
    }
  })
  return flag
}

function createFlyio() {
  let flyio = new Flyio()
  flyio.interceptors.request.use((requestConfig) => {
    // console.log(requestConfig, operate)

    requestConfig.headers['appVersion'] = config.appVersion

    requestConfig.WX_NOT_SEND = false

    if (
      checkIncludes(authSysPath, requestConfig.url)
    ) {
      requestConfig.headers['auth-sys'] = 'agent'
    }

    // token create 接口不加token
    if (
      checkIncludes(notTokenPath, requestConfig.url)
    ) {

      console.log('notTokenPath')
      return requestConfig
    }

    let token = Auth.getToken()
    if (token) {
      requestConfig.headers['token'] = token
    } else {
      console.log('没有token', requestConfig)
      let err =
        ['TOKEN_NOT_EXISTS_WHEN_REQUEST', new Error('token not exits')]
      console.error.apply(console, err)

      requestConfig.WX_NOT_SEND = true
    }
    console.log('requestConfig', requestConfig)
    return requestConfig
  })
  return flyio
}

function genErr(res) {
  if (res && res.data && res.data.hasOwnProperty('msg')) {
    return new Error(res.data.msg ? res.data.msg : 'unknown error')
  }
  return new Error(res ? res.msg : 'unknown error')
}

class CommonRequest extends Request {
  constructor(...args) {
    super(...args)
    this.navigationBarLoading = false
    this.showLoading = true
    this.showError = true
    this.needHandleErr = true
    this._debug = false
  }

  handleServerErr(e) {
  }

  fetch(method, args) {
    let self = this
    return new Promise( (resolve, reject) => {
      self.showLoadingUI()

      super._request(method, ...args).then(res => {
        let isOk = this.handleRetError(res)
        if (isOk) {
          resolve(res ? res.data : '')
        }
        self.hideLoadingUI()
        let err = genErr(res)
      }).catch(err => {
        self.handleErr(err)
        reject(err)
      })
    })
  }

  get(...args) {
    return this.fetch('get', args)
  }

  post(...args) {
    return this.fetch('post', args)
  }

  put(...args) {
    return this.fetch('put', args)
  }

  delete(...args) {
    return this.fetch('delete', args)
  }

  showLoadingUI() {
    if (this.navigationBarLoading) {
      wx.showNavigationBarLoading()
    }
    if (this.showLoading) {
      wx.showLoading({
        title: '-玩儿命加载中-',
      })
    }
  }

  hideLoadingUI() {
    if (this.navigationBarLoading) {
      wx.hideNavigationBarLoading()
    }
    if (this.showLoading) {
      wx.hideLoading()
    }
  }

  handleRetError(res) {
    console.log('res code', res, this.needHandleErr)
    if (!this.needHandleErr) {
      return true
    }
    let canGoNext = true
    if (res && res.data && res.data.code) {
      if (this.handleErrCode) {
        canGoNext = this.handleErrCode(res.data.code, res)
      }
    }
    if (canGoNext) {
      let err = new Error(
        res && res.data ? `${res.data.msg}` : 'server unknown error')
      let shouldHandleErr =
        this.shouldCatchErr ?
          this.shouldCatchErr(res) :
          (!res || !res.data || !res.data.code || res.data.code > 20000)
      if (shouldHandleErr) {
        this.handleErr(err, res)
        return false
      }
    }
    return true
  }

  handleErr(err, res) {
    console.error('handleErr', err, res)
    if (this.showError) {
      let message = err.message || err.msg || ''
      if (this.handleErrMessage) {
        this.handleErrMessage(message, err, res, config, this)
      }
    }
  }

}

let nio = {
  createFlyio,
  initRequest(flyio, conf = {}) {
    return new CommonRequest(flyio, {
      base: '',
      ...conf,
    })
  }
}

export {
  nio
}
